package com.smart4j.framework.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import lombok.extern.slf4j.Slf4j;

/**
 * 反射工具类
 *
 * @author 段誉
 * @create 2019-03-28 20:55
 */
@Slf4j
public final class ReflectionUtil {
  /**
   * 创建实例
   */
  public static Object newInstance(Class<?> cls) {
    Object instance;
    try {
      instance = cls.newInstance();
    } catch (Exception e) {
      log.error("new instance failure", e);
      throw new RuntimeException(e);
    }
    return instance;
  }

  /**
   * 调用方法
   */
  public static Object invokeMethod(Object obj, Method method, Object...args) {
    Object result;
    try {
      //设置启用/禁用安全检测，设置为true后再性能上有所提升，
      // 原因：设置为true表示反射的对象正在使用时应该取消java语言的访问查询
      method.setAccessible(true);
      result = method.invoke(obj, args);
    } catch (Exception e) {
      log.error("invoke method failure", e);
      throw new RuntimeException(e);
    }
    return result;
  }

  /**
   * 设置成员变量的值
   */
  public static void setField(Object obj, Field field, Object value) {
    try {
      field.setAccessible(true);
      field.set(obj, value);
    } catch (IllegalAccessException e) {
      log.error("set field failure", e);
      throw new RuntimeException(e);
    }
  }
}
